package org.zj.springstyle.mvc.parseJSON;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by zhaoji on 14/12/24.
 */
public class ParseJSON {

    public static String ReadFile(String Path){
        BufferedReader reader = null;
        String laststr = "";
        try{
            FileInputStream fileInputStream = new FileInputStream(Path);
            InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream, "UTF-8");
            reader = new BufferedReader(inputStreamReader);
            String tempString = null;
            while((tempString = reader.readLine()) != null){
                laststr += tempString;
            }
            reader.close();
        }catch(IOException e){
            e.printStackTrace();
        }finally{
            if(reader != null){
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return laststr;
    }

    public static Map<String,NativatorBean> parseJSON(String jsonPath){
        String JsonContext = ParseJSON.ReadFile(jsonPath);
        JSONArray jsonArrays = JSONArray.parseArray(JsonContext);
        int size = jsonArrays.size();
        System.out.println("Size: " + size);
        Map<String,NativatorBean> nativatorMap = new HashMap<String, NativatorBean>();
        Map<String,String> nativator = null;
        NativatorBean nb = null;
        for(int  i = 0; i < size; i++){
            nativator = new HashMap<String, String>();
            JSONObject jsonObject = jsonArrays.getJSONObject(i);
            nb = new NativatorBean();
            nb.setPath(jsonObject.get("path").toString());
            nb.setControllerClass(jsonObject.get("controllerClass").toString());
            nb.setFormBeanClass(jsonObject.get("formBeanClass").toString());
            nb.setFormBeanName(jsonObject.get("formBeanName").toString());
            JSONArray jsonArrays2 = JSONArray.parseArray(jsonObject.get("forward").toString());
            for(int j = 0; j < jsonArrays2.size(); j++){
                JSONObject jsonObject2 = jsonArrays2.getJSONObject(j);
                nativator.put(jsonObject2.get("accessName").toString(),jsonObject2.get("accessPath").toString());
            }
            nb.setMap(nativator);
            nativatorMap.put(jsonObject.get("path").toString(),nb);
        }
        return nativatorMap;
    }

    public static void main(String []args){

    }
}